<template>
    <view class="address-con">
        <!-- 头部搜索区域 -->
        <view class="header">
            <view class="location-selector" @click="showRegion = true">
                <u-icon name="map" color="#0785CF" size="32rpx"></u-icon>
                <text class="location-text">{{ selectedCity.city || selectedCity.province || '请选择' }}</text>
                <u-icon name="arrow-down" color="#0785CF" size="24rpx"></u-icon>
            </view>
            <view class="search-box">
                <input 
                    class="search-input" 
                    placeholder="请输入小区名称" 
                    v-model="searchKeyword"
                    @input="onSearchInput"
                />
            </view>
        </view>
        
        <!-- 小区列表 -->
        <view class="community-list">
            <view 
                class="community-card" 
                v-for="(community, index) in filteredCommunities" 
                :key="index"
                @click="selectCommunity(community)"
            >
                <view class="community-info">
                    <text class="community-name">{{ community.title }}</text>
                    <text class="community-address">{{ community.province_name }}/{{ community.city_name }}/{{ community.district_name }}</text>
                </view>
                <view class="select-btn" :class="{ active: currentSelectedCommunity && currentSelectedCommunity.id === community.id }">
                    <text class="btn-text">{{ currentSelectedCommunity && currentSelectedCommunity.id === community.id ? '已选择' : '选择' }}</text>
                </view>
            </view>
        </view>
        
        <!-- 加载更多提示 -->
        <u-loadmore :status="loadStatus" />
        
        <!-- 地区选择弹窗 -->
        <u-picker 
            :show="showRegion" 
            :columns="regionColumns" 
            title="请选择地区" 
            @change="onRegionPickerChange"
            @confirm="onRegionConfirm" 
            @cancel="showRegion = false"
            @close="showRegion = false"
        />
    </view>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import { getprovince, getcity, getNeighborSearchHousing } from '@/api/index.js'

export default {
    data() {
        return {
            searchKeyword: '',
            // 地区选择（仅省/市）
            showRegion: false,
            regionColumns: [],
            provinceList: [],
            cityList: [],
            communities: [],
            // 分页与加载状态
            page: 1,
            limit: 10,
            loading: false,
            finished: false
        }
    },
    computed: {
        ...mapState(['selectedCity', 'communitySelectType', 'selectedPickupCommunity', 'selectedDeliveryCommunity']),
        loadStatus() {
            if (this.loading) return 'loading'
            if (this.finished) return 'nomore'
            return 'loadmore'
        },
        filteredCommunities() {
            return this.communities
        },
        currentSelectedCommunity() {
            if (this.communitySelectType === 'pickup') {
                return this.selectedPickupCommunity;
            } else if (this.communitySelectType === 'delivery') {
                return this.selectedDeliveryCommunity;
            }
            return null;
        }
    },
    mounted() {
        // 初始化在 getprovinceEvent 完成后拉取
    },
    methods: {
        ...mapActions(['setSelectedCity', 'setSelectedPickupCommunity', 'setSelectedDeliveryCommunity', 'getAddressList']),
        async getNeighborSearchHousingEvent() {
            if (this.loading || this.finished) return
            this.loading = true
            console.log(this.selectedCity.province, this.selectedCity.city)
            try {
                const res = await getNeighborSearchHousing({
                    province_name: this.selectedCity.province || (this.provinceList[0] && this.provinceList[0].name) || '',
                    city_name: this.selectedCity.city || (this.cityList[0] && this.cityList[0].name) || '',
                    keyword: this.searchKeyword,
                    page: this.page,
                    limit: this.limit
                })
                if (res && res.errno === 0) {
                    const list = Array.isArray(res.data) ? res.data : (res.data && Array.isArray(res.data.list) ? res.data.list : [])
                    if (this.page === 1) {
                        this.communities = list
                    } else {
                        this.communities = this.communities.concat(list)
                    }
                    if (list.length < this.limit) this.finished = true
                }
            } catch (e) {
                // ignore
            } finally {
                this.loading = false
            }
        },
        resetAndFetch() {
            this.page = 1
            this.finished = false
            this.communities = []
            this.getNeighborSearchHousingEvent()
        },
        onSearchInput() {
            // 关键字变化后重置并请求
            this.resetAndFetch()
        },
        selectCommunity(community) {
            // 根据选择类型设置对应的社区
            if (this.communitySelectType === 'pickup') {
                this.setSelectedPickupCommunity(community);
            } else if (this.communitySelectType === 'delivery') {
                this.setSelectedDeliveryCommunity(community);
            }
            
            // 延迟一下再返回，让用户看到选择效果
            setTimeout(() => {
                uni.navigateBack({
                    delta: 1
                });
            }, 300);
        },
        onRegionConfirm(e) {
            const values = e?.value || []
            const [pName, cName] = values
            // 设置选中的省/市（若无市则仅省）
            this.setSelectedCity({ province: pName || '', city: cName || '' })
            this.showRegion = false
            this.resetAndFetch()
        },
        onRegionPickerChange(e) {
            const columnIndex = (e && (e.columnIndex ?? e.column)) ?? 0
            // 省列变化 -> 刷新市列
            if (columnIndex === 0) {
                const provinceIndex = (e && (e.index ?? (Array.isArray(e.indexs) ? e.indexs[0] : 0))) ?? 0
                const province = this.provinceList[provinceIndex]
                if (province && province.id) {
                    this.getcityEvent(province.id)
                } else {
                    this.$set(this.regionColumns, 1, [])
                }
            }
        },
        getprovinceEvent() {
            getprovince().then((res) => {
                if (res && res.errno === 0) {
                    const list = Array.isArray(res.data) ? res.data : []
                    this.provinceList = list
                    const provinceNames = list.map(item => item && item.name ? item.name : '')
                    // 两列：省/市
                    this.regionColumns = [provinceNames, []]
                    const firstProvinceId = list[0] && list[0].id
                    if (firstProvinceId) {
                        this.getcityEvent(firstProvinceId).then(async () => {
                            // 初始化：优先 store 中的省市；否则默认取第一个
                            if (!this.selectedCity || (!this.selectedCity.city && !this.selectedCity.province)) {
                                const provinceName = (this.provinceList[0] && this.provinceList[0].name) || ''
                                const cityName = (this.cityList[0] && this.cityList[0].name) || ''
                                await this.setSelectedCity({ province: provinceName, city: cityName })
                            }
                            this.resetAndFetch()
                        })
                    }
                } else {
                    this.regionColumns = [[], []]
                }
            }).catch(() => {
                this.regionColumns = [[], []]
            })
        },
        getcityEvent(pid) {
            if (!pid) return Promise.resolve()
            return new Promise((resolve) => {
                getcity({ pid }).then((res) => {
                    if (res && res.errno === 0) {
                        const list = Array.isArray(res.data) ? res.data : []
                        const names = list.map(item => item && item.name ? item.name : '')
                        this.cityList = list
                        this.$set(this.regionColumns, 1, names)
                        resolve()
                    } else {
                        this.$set(this.regionColumns, 1, [])
                        resolve()
                    }
                }).catch(() => {
                    this.$set(this.regionColumns, 1, [])
                    resolve()
                })
            })
        },
    },
    onLoad(option) {
        // 获取选择类型参数
        if (option.type) {
            this.$store.commit('SET_COMMUNITY_SELECT_TYPE', option.type);
        }
        // 优先使用store中已有选择；若无则从地址接口默认/第一个初始化
        Promise.resolve()
            .then(async () => {
                const hasStoreCity = this.selectedCity && (this.selectedCity.city || this.selectedCity.province)
                if (!hasStoreCity) {
                    const list = await this.getAddressList()
                    const defaultAddr = this.$store.getters.defaultAddress
                    const firstAddr = Array.isArray(list) && list.length ? list[0] : null
                    const useAddr = defaultAddr || firstAddr
                    if (useAddr) {
                        await this.setSelectedCity({ province: useAddr.province_name || '', city: useAddr.city_name || '' })
                    }
                }
            })
            .finally(() => {
                // 加载省市并根据当前store城市发起首请求
                this.getprovinceEvent()
            })
    },
    onReachBottom() {
        if (this.loading || this.finished) return
        this.page += 1
        this.getNeighborSearchHousingEvent()
    }
}
</script>

<style lang="scss" scoped>
.address-con {
    width: 100%;
    min-height: 100vh;
    background: #F6F6F6;
}

/* 头部区域 */
.header {
    padding: 24rpx 32rpx;
    display: flex;
    align-items: center;
    background: #fff;
}

.location-selector {
    display: flex;
    align-items: center;
    gap: 8rpx;
    height: 72rpx;
    background: #E7F0FF;
    min-width: 160rpx;
    padding-left: 28rpx;
    border-radius: 60rpx 0 0 60rpx;
}

.location-text {
    font-size: 28rpx;
    color: #0785CF;
}

.search-box {
    flex: 1;
    display: flex;
    align-items: center;
    gap: 16rpx;
    background: #E7F0FF;
    border-radius: 8rpx;
    padding: 16rpx 20rpx;
    border-radius: 0 60rpx 60rpx  0;
}

.search-input {
    flex: 1;
    font-size: 28rpx;
    color: #333;
}

/* 小区列表 */
.community-list {
    padding: 24rpx 32rpx;
}

.community-card {
    background: #FFFFFF;
    padding: 32rpx;
    margin-bottom: 24rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-shadow: 0rpx 4rpx 20rpx 0rpx rgba(0,0,0,0.06);
    border-radius: 20rpx 20rpx 20rpx 20rpx;
}

.community-info {
    flex: 1;
}

.community-name {
    display: block;
    font-size: 32rpx;
    color: #333;
    font-weight: 600;
    margin-bottom: 8rpx;
}

.community-address {
    display: block;
    font-size: 24rpx;
    color: #999;
}

.select-btn {
    width: 136rpx;
    height: 52rpx;
    background: #25A4EF;
    box-shadow: 0rpx 4rpx 8rpx 0rpx rgba(37,164,239,0.1);
    border-radius: 60rpx 60rpx 60rpx 60rpx;
    text-align: center;
    transition: all 0.3s ease;
    
    &.active {
        background: #0785CF;
        box-shadow: 0rpx 4rpx 8rpx 0rpx rgba(7,133,207,0.2);
    }
}

.btn-text {
    font-size: 28rpx;
    color: #FFFFFF;
    text-align: center;
    line-height: 52rpx;
}
</style>